<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      label-width="120px">
      <el-row>
        <el-form-item label="积分项目名称" prop="itemName">
          <el-input v-model="queryParams.itemName" placeholder="请输入积分项目名称" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <!-- <el-form-item label="状态" prop="dataStatus">
          <el-select
            v-model="queryParams.dataStatus"
            placeholder="请选择状态"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item style="margin-left: 22px">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row class="row-mbinfo">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left: 10px">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
         >修改</el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left: 10px">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          >删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column label="积分项目名称" align="center" prop="itemName" />
        <el-table-column label="积分项目类别" align="center" prop="itemTypeStr" />

        <el-table-column label="积分值" align="center" prop="score" />

        <el-table-column label="创建人" align="center" prop="createName" />


        <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable>
          <template slot-scope="scope">
            <span>{{
    parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
}}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" prop="dataStatus" min-width="120">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.dataStatus" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              >修改</el-button>
            <el-button v-if="scope.row.dataStatus == '0'" size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改积分项目/系列对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body @keyup.enter.native="submitForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="积分项目名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入积分项目名称" class="select-normal" maxlength="20"
            show-word-limit />
        </el-form-item>



        <el-form-item label="积分项目" prop="itemType">
          <el-radio v-model="form.itemType" label="add">增分项</el-radio>
          <el-radio v-model="form.itemType" label="reduce">减分项</el-radio>
          <!-- <el-radio v-model="form.itemType" label="reward">奖励项</el-radio> -->
        </el-form-item>



        <el-form-item label="积分值" prop="score">
          <el-input v-model="form.score" placeholder="请输入项目积分值" class="select-normal" maxlength="10"
            @input="form.score = onInput(form.score, 0)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listItem,
  getItem,
  delItem,
  addItem,
  updateItem,
  updateItemStatus,
} from "@/api/service/score";
import { onInput } from "@/utils/util";
import imageArraySize from "@/components/ImageUpload/imageArraySize";
export default {
  name: "Item",
  components: {
    imageArraySize,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中数组的名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 积分项目/系列表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用于类别关联的分类显示
      dialogVisible: false,
      //常用状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemName: null,
        dataStatus: null,
      },

      // 表单参数
      form: {
        dialogImageUrl: "",
        dataPriority: "",
      },
      // 表单校验
      rules: {
        itemName: [
          {
            required: true,
            message: "积分项目名称不能为空",
            trigger: "blur",
          },
        ],
        dataPriority: [
          {
            required: true,
            message: "排序不能为空",
            trigger: "blur",
          },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_data_status").then((response) => {
      this.statusOptions = response.data;
    });
  },
  methods: {

    onInput,
    dataPriorityInput(value) {
      let js = value + "";
      return js.replace(/^(0+)|[^\d]+/g, "");
    },
    /** 查询积分项目/系列列表 */
    getList() {
      this.loading = true;
      listItem(this.queryParams).then((response) => {
        this.brandList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleRemove(file, fileList) { },
    handlePictureCardPreviewLogo(file) {
      this.logoUr = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreviewImg(file) {
      this.deviceImage = file.url;
      this.dialogVisible = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 关联的取消按钮
    cancelItem() {
      this.openItem = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        itemName: null,
        logoUrl: null,
        itemType: null,
        deviceImage: null,
        dataPriority: 10,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 积分项目菜单 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.itemId);
      this.names = selection.map((item) => item.itemName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.dataStatus) {
            this.multiple = true;
            break;
          }
        }
      }
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.dataStatus === "0" ? "无效" : "有效";
      this.$confirm(
        '确定要把积分项目名称为"' + row.itemName + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateItemStatus(row.itemId, row.dataStatus);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加积分项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const itemId = row.itemId || this.ids;
      getItem(itemId).then((response) => {
        this.form = response.data;
        console.log(this.form);
        if (response.data.itemType == "reduce")
          this.form.score = response.data.score * -1;
        console.log(this.form);
        this.open = true;
        this.title = "修改积分项目";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.itemId != null) {
            updateItem(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addItem(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const itemIds = row.itemId || this.ids;
      const names = row.itemName || this.names;
      this.$confirm('是否确认删除积分项目名称为"' + names + '"的积分项目?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delItem(itemIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "device/brand/export",
        {
          ...this.queryParams,
        },
        `商品积分项目.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.treeOne {
  display: inline-block;
  margin-right: 200px;
}

.treeTwo {
  display: inline-block;
}

.image-rows {
  width: 80px;
  height: auto;
}
</style>
